package com.example.factory.api.facade.impl;

import com.example.factory.api.dto.DtoDepartment;
import com.example.factory.api.dto.PageResponse;
import com.example.factory.api.dto.Response;
import com.example.factory.api.dto.form.DtoDepartmentForm;
import com.example.factory.api.dto.form.DtoQueryDepartmentListForm;
import com.example.factory.api.facade.DepartmentFacade;
import com.example.factory.api.dto.assembler.DepartmentAssembler;
import com.example.factory.core.domain.Department;
import com.example.factory.core.repository.DepartmentRepository;
import com.example.factory.core.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lei Tao
 */
@Service
public class DepartmentFacadeImpl implements DepartmentFacade {
    private final DepartmentService departmentService;
    private final DepartmentRepository departmentRepository;
    private final DepartmentAssembler departmentAssembler;

    @Autowired
    public DepartmentFacadeImpl(DepartmentService departmentService, DepartmentRepository departmentRepository, DepartmentAssembler departmentAssembler) {
        this.departmentService = departmentService;
        this.departmentRepository = departmentRepository;
        this.departmentAssembler = departmentAssembler;
    }

    @Override
    public Response<List<DtoDepartment>> departmentList(DtoQueryDepartmentListForm dtoQueryDepartmentListForm) {
        Page<Department> departments = departmentRepository.findDepartments(dtoQueryDepartmentListForm);
        List<DtoDepartment> dtoDepartments = departmentAssembler.toDtoDepartments(departments);
        int totalPages = departments.getTotalPages();
        long totalElements = departments.getTotalElements();
        return PageResponse.success(totalElements, totalPages, dtoDepartments);
    }

    @Override
    public Response<DtoDepartment> saveOrUpdateDepartment(DtoDepartmentForm dtoDepartmentForm) {
        Department department = departmentAssembler.toDepartment(dtoDepartmentForm);
        departmentService.save(department);
        DtoDepartment dtoDepartment = departmentAssembler.toDtoDepartment(department);
        return Response.success(dtoDepartment);
    }

    @Override
    public Response<Void> deleteDepartment(String departmentGuid) {
        departmentService.deleteDepartment(departmentGuid);
        return Response.success();
    }

    @Override
    public Response<DtoDepartment> retrieveDepartment(String departmentGuid) {
        Department department = departmentService.findDepartment(departmentGuid);
        if (department == null){
            return Response.failed(2001);
        }
        DtoDepartment dtoDepartment = departmentAssembler.toDtoDepartment(department);
        return Response.success(dtoDepartment);
    }
}
